package com.ruoyi.develop.lvYifahuo.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.lvYifahuomingxi.domain.LvYifahuomingxi;
import com.ruoyi.develop.lvYifahuomingxi.service.ILvYifahuomingxiService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.lvYifahuo.domain.LvYifahuo;
import com.ruoyi.develop.lvYifahuo.service.ILvYifahuoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 发货单Controller
 * @author qh
 * @date 2024-10-08
 */
@RestController
@RequestMapping("/lvYifahuo/lvYifahuo")
public class LvYifahuoController extends BaseController {
    @Autowired
    private ILvYifahuoService lvYifahuoService;
    @Autowired
    private ILvYifahuomingxiService iLvYifahuomingxiService;
    /**
     * 查询发货单列表
     */
    @PreAuthorize("@ss.hasPermi('develop:LvYifahuo:query')")
    @GetMapping("/list")
    public TableDataInfo list(LvYifahuo entity) {
        startPage();
        List<LvYifahuo> list = lvYifahuoService.selectList(entity);
        return getDataTable(list);
    }

    /**
     * 导出发货单列表
     */
    @PreAuthorize("@ss.hasPermi('develop:LvYifahuo:export')")
    @Log(title = "发货单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LvYifahuo entity) {
        List<LvYifahuo> list = lvYifahuoService.selectList(entity);
        ExcelUtil<LvYifahuo> util = new ExcelUtil<LvYifahuo>(LvYifahuo. class);
        util.exportExcel(response, list, "发货单数据");
    }

    /**
     * 获取发货单详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:LvYifahuo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(lvYifahuoService.selectById(id));
    }

    /**
     * 新增发货单
     */
    @PreAuthorize("@ss.hasPermi('develop:LvYifahuo:add')")
    @Log(title = "发货单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody LvYifahuo entity) {
        //查询未提交产品
         LvYifahuomingxi lvYifahuomingxi=iLvYifahuomingxiService.selectWeikaMoney(BusinessConstants.YIFAHUO_0);
        //更新发货金额和未开票金额
        entity.setAllMoney(lvYifahuomingxi.getMoney());
        entity.setShengyu(lvYifahuomingxi.getMoney());
        entity.setTaxAllmoeny(lvYifahuomingxi.getMoney());
        entity.setTaxShengyu(lvYifahuomingxi.getMoney());
        entity.setStatus(BusinessConstants.YIFAHUO_1);
        String proNo="";
        //查询未提交产品
        List<LvYifahuomingxi> LvYifahuomingxiList=iLvYifahuomingxiService.selectByFahuoIdDistinctProNoZancun();
        if(LvYifahuomingxiList.size()>0) {
            for (LvYifahuomingxi lvYifahuomingxi1 : LvYifahuomingxiList) {
                proNo = proNo + lvYifahuomingxi1.getProNo() + ",";
            }
        }
        entity.setProjectNos(proNo);
        lvYifahuoService.insert(entity);
        iLvYifahuomingxiService.updateDate(entity.getTongzhiId(),entity.getId(),entity.getFahuoDate(),entity.getJiaohuoDate());
        iLvYifahuomingxiService.updateByFahuoId(entity.getTongzhiId(),entity.getId(),entity.getNos(),BusinessConstants.YIFAHUO_1);
        String projectNos="";
        List<LvYifahuomingxi> lvYifahuomingxiList=iLvYifahuomingxiService.selectByFahuoIdGrouByProid(entity.getId());
        for(LvYifahuomingxi lvFahuomingxi :lvYifahuomingxiList){
            projectNos=projectNos+lvFahuomingxi.getProNo()+",";
        }
        if(entity.getColumns().size()>0){
            entity.setSaleman(entity.getColumns().get(0).getSaleman());
        }

        entity.setProjectNos(projectNos);
        return toAjax(lvYifahuoService.update(entity));
    }

    @PreAuthorize("@ss.hasPermi('develop:LvYifahuo:add')")
    @Log(title = "发货单", businessType = BusinessType.INSERT)
    @PostMapping("/addZancun")
    public AjaxResult addZancun(@RequestBody LvYifahuo entity) {
        List<LvYifahuomingxi> lvYifahuomingxiList=entity.getColumns();
        BigDecimal totalMoney=new BigDecimal(0);
        StringBuilder projectNos= new StringBuilder();
        String salesman="";
        for(LvYifahuomingxi lvYifahuomingxi:lvYifahuomingxiList){
            totalMoney=totalMoney.add(lvYifahuomingxi.getMoney());
            projectNos.append(lvYifahuomingxi.getProNo()).append(",");
            salesman = lvYifahuomingxi.getSaleman();
        }

        if(StringUtils.isNotBlank(projectNos.toString())){
            String[] projectNosStr = projectNos.toString().split(",");
            String[] uniqueNos= Arrays.stream(projectNosStr).distinct().toArray(String[]::new);
            String resultNos = String.join(",", uniqueNos);
            entity.setProjectNos(resultNos);
        }

        entity.setAllMoney(totalMoney);
        entity.setShengyu(totalMoney);
        entity.setTaxAllmoeny(totalMoney);
        entity.setTaxShengyu(totalMoney);
        entity.setStatus(BusinessConstants.YIFAHUO_0);
        entity.setSaleman(salesman);
        if(StringUtils.isBlank(entity.getId())){
            lvYifahuoService.insert(entity);
        }else{
            lvYifahuoService.update(entity);
        }
        for(LvYifahuomingxi lvYifahuomingxi:lvYifahuomingxiList){
            lvYifahuomingxi.setFahuoId(entity.getId());
            lvYifahuomingxi.setFahuoNo(entity.getNos());
            lvYifahuomingxi.setFahuoDate(entity.getFahuoDate());
            lvYifahuomingxi.setJiaohuoDate(entity.getJiaohuoDate());
            lvYifahuomingxi.setStatus(BusinessConstants.YIFAHUO_5);
            iLvYifahuomingxiService.update(lvYifahuomingxi);
        }
        return toAjax(1);
    }

    /**
     * 驳回重新提交
     */
    @PreAuthorize("@ss.hasPermi('develop:LvYifahuo:edit')")
    @Log(title = "驳回重新提交", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody LvYifahuo entity) {
        //查询驳回产品或者未发货产品
        LvYifahuomingxi lvYifahuomingxi=iLvYifahuomingxiService.selectWeikaMoneyQishen( entity.getId());
        //更新发货金额和未开票金额
        entity.setAllMoney(lvYifahuomingxi.getMoney());
        entity.setShengyu(lvYifahuomingxi.getMoney());
        entity.setTaxAllmoeny(lvYifahuomingxi.getMoney());
        entity.setTaxShengyu(lvYifahuomingxi.getMoney());
        entity.setStatus(BusinessConstants.YIFAHUO_1);

        String proNo="";
        List<LvYifahuomingxi> LvYifahuomingxiList=iLvYifahuomingxiService.selectByFahuoIdDistinctProNo(entity.getId());
        if(LvYifahuomingxiList.size()>0) {
            for (LvYifahuomingxi lvYifahuomingxi1 : LvYifahuomingxiList) {
                proNo = proNo + lvYifahuomingxi1.getProNo() + ",";
            }
        }
        if(entity.getColumns().size()>0){
            entity.setSaleman(entity.getColumns().get(0).getSaleman());
        }
        entity.setProjectNos(proNo);
        lvYifahuoService.update(entity);
        return toAjax(iLvYifahuomingxiService.updateByFahuoIdQishen(entity.getId(),BusinessConstants.YIFAHUO_1));
    }

    @Log(title = "暂存发货单", businessType = BusinessType.UPDATE)
    @PutMapping("/editDaitijiao")
    public AjaxResult editDaitijiao(@RequestBody LvYifahuo entity) {
        //查询驳回产品或者未发货产品
        LvYifahuomingxi lvYifahuomingxi=iLvYifahuomingxiService.selectWeikaMoneyQishen( entity.getId());
        //更新发货金额和未开票金额
        entity.setAllMoney(lvYifahuomingxi.getMoney());
        entity.setShengyu(lvYifahuomingxi.getMoney());
        entity.setTaxAllmoeny(lvYifahuomingxi.getMoney());
        entity.setTaxShengyu(lvYifahuomingxi.getMoney());
        entity.setStatus(BusinessConstants.YIFAHUO_0);

        String proNo="";
        List<LvYifahuomingxi> LvYifahuomingxiList=iLvYifahuomingxiService.selectByFahuoIdDistinctProNo(entity.getId());
        if(LvYifahuomingxiList.size()>0) {
            for (LvYifahuomingxi lvYifahuomingxi1 : LvYifahuomingxiList) {
                proNo = proNo + lvYifahuomingxi1.getProNo() + ",";
            }
        }
        if(entity.getColumns().size()>0){
            entity.setSaleman(entity.getColumns().get(0).getSaleman());
        }
        entity.setProjectNos(proNo);
        lvYifahuoService.update(entity);
        return toAjax(iLvYifahuomingxiService.updateByFahuoIdQishen(entity.getId(),BusinessConstants.YIFAHUO_1));
    }


    @Log(title = "提交过磅单", businessType = BusinessType.UPDATE)
    @PutMapping("/editGuobangdan")
    public AjaxResult editGuobangdan(@RequestBody LvYifahuo entity) {
        return toAjax(lvYifahuoService.update(entity));
    }

    @Log(title = "到货回执", businessType = BusinessType.UPDATE)
    @PutMapping("/daohuohuizhi")
    public AjaxResult daohuohuizhi(@RequestBody LvYifahuo entity){
        return toAjax(lvYifahuoService.updateDaohuohuizhi(entity));
    }
    //弃审
    @PutMapping("/bohui")
    public AjaxResult bohui(@RequestBody LvYifahuo entity) {
        entity.setStatus(BusinessConstants.YIFAHUO_3);
        iLvYifahuomingxiService.updateStatusByFahuoId(entity.getId(),BusinessConstants.YIFAHUO_3);
        return toAjax(lvYifahuoService.update(entity));
    }
    /**
     * 删除发货单
     */
    @PreAuthorize("@ss.hasPermi('develop:LvYifahuo:remove')")
    @Log(title = "删除发货单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(lvYifahuoService.deleteByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('develop:LvYifahuo:remove')")
    @Log(title = "删除发货单", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{id}")
    public AjaxResult removeById(@PathVariable String id) {
        List<LvYifahuomingxi> lvYifahuomingxi=iLvYifahuomingxiService.selectByFahuoId(id);
        if(lvYifahuomingxi.size()>0){
            return AjaxResult.error("该通知单下有发货的产品，请弃审产品后删除！");
        }else{
            return toAjax(lvYifahuoService.deleteById(id));
        }
    }
    //审核发货单完成（出库单）
    @DeleteMapping("/shenhetongguo/{id}")
    public AjaxResult shenhetongguo(@PathVariable String id) {
        return toAjax(lvYifahuoService.shenhetongguo(id));
    }

    //库管提交发货单到财务审核
    @DeleteMapping("/tishenCaiwu/{id}")
    public AjaxResult tishenCaiwu(@PathVariable String id) {
        return toAjax(lvYifahuoService.tishenCaiwu(id));
    }



    /**
     * 财务确认发货
     */
    @PreAuthorize("@ss.hasPermi('develop:LvYifahuo:financeConfirm')")
    @GetMapping(value = "/financeConfirm/{id}")
    public AjaxResult financeConfirm(@PathVariable("id") String id) {
        return AjaxResult.success(lvYifahuoService.financeConfirm(id));
    }





}
